<template>
  <div class="create-box">
    <div class="header">需求大厅-发布</div>
    <a-form ref="formRef" :model="formState" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol" @finish="onFinish">
      <a-row>
        <a-col :span="3"><div class="create-title">关联需求收集单</div></a-col>
        <a-col :span="21">
          <a-form-item name="customerRequireFlag">
            <a-radio-group v-model:value="formState.customerRequireFlag">
              <a-radio :value="1">是</a-radio>
              <a-radio :value="2">否</a-radio>
            </a-radio-group>
            <a-form-item label="" name="customerRequireId" v-if="formState.customerRequireFlag === 1" class="create-order-select">
              <a-select style="width: 400px" placeholder="请选择" allowClear v-model:value="formState.customerRequireId" :filter-option="filterOption" @change="handleCustomerChange" show-search>
                <a-select-option v-for="item in list" :key="item.id" :value="item.id" :data-name="item.requireName">{{ item.requireName }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-form-item>
        </a-col>
      </a-row>

      <div class="create-title">基本信息</div>
      <a-form-item label="标题" name="requireName">
        <a-input v-model:value="formState.requireName" style="width: 400px" :maxlength="20" placeholder="请输入" />
      </a-form-item>
      <a-form-item label="类别" name="dictResultValue">
        <a-select v-model:value="formState.dictResultValue" placeholder="请选择" style="width: 400px" :labelInValue="true" mode="multiple">
          <a-select-option v-for="item in dictList" :key="item.code" :value="item.code">{{ item.name }}</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="周期" name="requireTime">
        <a-range-picker style="width: 400px" v-model:value="formState.requireTime" format="YYYY-MM-DD" valueFormat="YYYY-MM-DD" />
      </a-form-item>
      <a-form-item label="数量" name="requireAmount">
        <a-input-number v-model:value="formState.requireAmount" :min="1" />
      </a-form-item>
      <a-form-item label="预算" name="requireBudget">
        <a-input-number v-model:value="formState.requireBudget" :min="1" />
      </a-form-item>
      <a-form-item label="logo" name="requireLogo">
        <a-upload name="file" list-type="picture-card" :maxCount="1" class="avatar-uploader" :show-upload-list="false" :action="uploadApi" :headers="{ authorization: token }" :before-upload="beforeUploadLogo" @change="handleChange">
          <img v-if="formState.requireLogo" :src="formState.requireLogo" alt="avatar" class="logo-img" />
          <div v-else>
            <loading-outlined v-if="logoLoading" />
            <plus-outlined v-else />
            <div class="ant-upload-text">上传</div>
          </div>
        </a-upload>
      </a-form-item>
      <a-form-item label="描述" name="requireDesc">
        <a-textarea v-model:value="formState.requireDesc" style="width: 400px" :maxlength="200" placeholder="请输入" allow-clear />
      </a-form-item>
      <a-form-item label="标签" name="labels">
        <div class="label-box">
          <a-input v-model:value="label" placeholder="请输入" style="width: 200px" :maxlength="10" />
          <div class="label-btn" @click="addLabel()">+</div>
          <div class="label-list">
            <a-tag class="label-item" color="blue" closable @close="deleteLabel(index)" v-for="(item, index) in formState.labels" :key="item + index">{{ item }}</a-tag>
          </div>
        </div>
      </a-form-item>
      <a-form-item label="来源" name="requireSource">
        <a-input v-model:value="formState.requireSource" placeholder="请输入" style="width: 400px" />
      </a-form-item>

      <div class="create-title">具体要求</div>
      <a-form-item label="类型" name="dataType">
        <a-select v-model:value="formState.dataType" placeholder="请选择" style="width: 400px">
          <a-select-option v-for="item in dataTypeList" :key="item.code" :value="item.code">{{ item.name }}</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="大小" name="dataLimit">
        <a-select v-model:value="formState.dataLimit" placeholder="请选择" style="width: 400px">
          <a-select-option v-for="item in dataLimitList" :key="item.code" :value="item.code">{{ item.name }}</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="要求" name="techRequire">
        <a-textarea v-model:value="formState.techRequire" :maxlength="200" placeholder="请输入" allow-clear style="width: 400px" />
      </a-form-item>
      <a-form-item label="样例" name="sampleTempList">
        <a-upload v-model:file-list="formState.sampleTempList" :maxCount="9" @remove="handleRemove" :before-upload="beforeUpload">
          <a-button :loading="loading">
            <upload-outlined v-if="!loading" />
            上传
          </a-button>
        </a-upload>
      </a-form-item>
      <a-form-item label="资质" name="qualificationsFlag">
        <a-radio-group v-model:value="formState.qualificationsFlag">
          <a-radio :value="1">是</a-radio>
          <a-radio :value="0">否</a-radio>
        </a-radio-group>
        <a-form-item label="" name="qualificationsDesc" v-if="formState.qualificationsFlag === 1" class="create-order-select">
          <a-textarea v-model:value="formState.qualificationsDesc" :maxlength="100" placeholder="请输入" style="width: 400px" />
        </a-form-item>
      </a-form-item>
      <a-form-item :wrapper-col="{ span: 12, offset: 3 }">
        <a-button type="primary" html-type="submit" :loading="submitLoading">发布</a-button>
        <a-button class="back-btn" @click="pageBack()">返回</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
  import { LoadingOutlined, PlusOutlined, UploadOutlined } from '@ant-design/icons-vue'
  import type { UploadChangeParam, UploadProps } from 'ant-design-vue'
  import { message, Upload } from 'ant-design-vue'
  import { v4 as uuidv4 } from 'uuid'
  import { onMounted, reactive, ref } from 'vue'
  import { useRoute, useRouter } from 'vue-router'

  import { getCustomerRequireData, getDictList, getRequireDetail, saveRequire, uploadFileList } from '/@/api/exchange/requirement'
  import { getToken } from '/@/storage'

  import { dataLimitList, dataTypeList } from './data'

  /** 基础数据 */
  const router = useRouter()
  const route = useRoute()
  const platformRequireId = route.query.id || ''

  const token = getToken() || ''
  const uploadApi = `${import.meta.env.VITE_BASE_API_PATH}/contentFile/upload/V1`
  const list = ref<RequirementTypes.IResponse[]>([])
  const dictList = ref<RequirementTypes.DictValueResponse[]>([])
  const dictObj = ref<RequirementTypes.StateData>()
  const label = ref<string>()
  const loading = ref(false)
  const submitLoading = ref(false)
  const logoLoading = ref(false)
  const sampleTemp = ref<RequirementTypes.sampleTempType[]>([])
  /** 表单数据 */
  const formRef = ref()
  const labelCol = { span: 3 }
  const wrapperCol = { span: 21 }
  const formState: UnwrapRef<RequirementTypes.SaveRequest> = reactive({
    customerRequireFlag: null,
    customerRequireId: undefined,
    requireName: null,
    dictResults: null,
    dictResultValue: [],
    requireBeginTime: null,
    requireEndTime: null,
    requireTime: null,
    requireAmount: null,
    requireBudget: null,
    requireDesc: null,
    labels: [],
    requireSource: null,
    dataType: undefined,
    dataLimit: undefined,
    techRequire: null,
    sampleTempList: [],
    qualificationsFlag: null,
    qualificationsDesc: null,
    requireLogo: null,
  })
  const rules: Record<string, Rule[]> = {
    customerRequireFlag: [{ required: true, message: '请选择是否关联需求单', trigger: 'change' }],
    customerRequireId: [{ required: true, message: '请选择需求单', trigger: 'change' }],
    requireName: [{ required: true, message: '请输入标题', trigger: 'change' }],
    dictResultValue: [{ required: true, message: '请选择类别', trigger: 'change' }],
    requireTime: [{ required: true, message: '请选择周期', trigger: 'change' }],
    requireAmount: [{ required: true, message: '请输入数量', trigger: 'change' }],
    requireBudget: [{ required: true, message: '请输入预算', trigger: 'change' }],
    labels: [{ required: true, message: '请输入标签' }],
    dataType: [{ required: true, message: '请选择类型', trigger: 'change' }],
    dataLimit: [{ required: true, message: '请选择大小', trigger: 'change' }],
    qualificationsDesc: [{ required: true, message: '请输入资质', trigger: 'change' }],
    requireLogo: [{ required: true, message: '请上传logo', trigger: 'blur' }],
    requireSource: [{ required: true, message: '请输入来源', trigger: 'change' }],
  }

  function getBase64(img: Blob, callback: (base64Url: string) => void) {
    const reader = new FileReader()
    reader.addEventListener('load', () => callback(reader.result as string))
    reader.readAsDataURL(img)
  }

  const filterOption = (input: string, option: any) => {
    return option['data-name'] && option['data-name'].toLowerCase().indexOf(input.toLowerCase()) >= 0
  }

  /** 新增标签 */
  const addLabel = () => {
    if (!label.value) {
      message.error('输入标签内容')
      return
    }
    if (formState.labels.length >= 10) {
      message.error('最多可添加10个标签')
      return
    }
    formState.labels.push(label.value)
    label.value = ''
  }
  /** 删除标签 */
  const deleteLabel = (index: number) => {
    formState.labels.splice(index, 1)
  }

  /** 上传图片 */
  const beforeUploadLogo = (file) => {
    console.log('\n\n---file', file)
    const isLt2M = file.size / 1024 / 1024 < 5
    const isType = ['.jpg', '.jpeg', '.png'].includes(file.name.substr(file.name.lastIndexOf('.')).toLowerCase())
    if (!isType) {
      message.error('不支持的格式文件')
      return false
    } else if (!isLt2M) {
      message.error('文件大小超过5MB，请选择一个较小的文件。')
      return false
    } else {
      return true
    }
  }
  const handleChange = (info) => {
    if (info.file.status === 'uploading') {
      logoLoading.value = true
      return
    }
    if (info.file.status === 'done') {
      message.success('上传成功')
      formState.requireLogo = info.file.response.responseData
      logoLoading.value = false
    }
    if (info.file.status === 'error') {
      logoLoading.value = false
      message.error(info.file.response.responseMessage || '上传错误')
    }
  }

  const beforeUpload = (file) => {
    const isLt2M = file.size / 1024 / 1024 < 10
    if (!isLt2M) {
      message.error('文件大小超过10MB，请选择一个较小的文件。')
      return false
    }
    console.log('\n\n---file', file)
    const { name } = file
    const fileExtension = name.split('.').pop()
    const newFileName = `${uuidv4()}.${fileExtension}` // 生成新的文件名，包含UUID和原文件扩展名
    const params = {
      file,
      name: newFileName,
      isDirectory: false,
      currentDir: '/',
      description: '',
      directoryType: 'FILE',
    }
    loading.value = true
    uploadFile(params)
    return false
  }
  const handleRemove = (file) => {
    const index = sampleTemp.value.findIndex((item) => item.fileUrl === file.uid)
    sampleTemp.value.splice(index, 1)
  }
  const uploadFile = async (params) => {
    const { responseCode, responseData } = await uploadFileList(params)
    if (responseCode === 100000000) {
      const { file } = params
      sampleTemp.value.push({
        fileId: responseData.data,
        fileName: file.name,
        fileType: file.type,
        fileSize: file.size,
        fileUrl: file.uid,
      })
      message.success('上传成功')
      loading.value = false
    } else {
      message.error('上传失败')
      loading.value = false
      logoLoading.value = false
    }
  }

  /** 选择类别 */
  const dictData = () => {
    let list = []
    formState.dictResultValue.map((item) => {
      console.log('item', item)
      list.push({
        code: item.key,
        name: typeof item.label === 'string' ? item.label : item.label[0].children,
      })
    })
    return {
      values: list,
      typeCode: dictObj.value.typeCode,
      typeName: dictObj.value.typeName,
    }
  }

  /**提交表单 */
  const onFinish = (values) => {
    submitLoading.value = true
    console.log('\n\n---values---', values)
    const params = {
      ...values,
      requireBeginTime: values.requireTime[0],
      requireEndTime: values.requireTime[1],
    }
    if (platformRequireId) {
      params.id = platformRequireId
    }
    if (sampleTemp.value.length) {
      params.sampleTemp = sampleTemp.value
    }
    if (formState.dictResultValue && formState.dictResultValue.length) {
      params.dictResults = dictData()
    }
    delete params.requireTime
    delete params.dictResultValue
    delete params.sampleTempList
    console.log('\n\n---params', params)
    onSubmit(params)
  }

  const onSubmit = async (params) => {
    const { responseCode } = await saveRequire(params)
    if (responseCode === 100000000) {
      message.success('保存成功')
      pageBack()
    } else {
      message.error('保存失败')
    }
    submitLoading.value = false
  }

  /**查看需求详情 */
  const goToDetail = (id: string) => {
    router.push({
      path: '/requirement/detail',
      query: { id },
    })
  }

  /**回退页面*/
  const pageBack = () => {
    router.back()
  }

  /**获取字典*/
  const getDictData = async () => {
    const params = { type: 'customer_require_type' }
    const { responseData } = await getDictList(params)
    if (responseData) {
      dictObj.value = {
        typeCode: responseData.typeCode,
        typeName: responseData.typeName,
      }
      dictList.value = responseData.values || []
    }
  }

  /**获取需求单列表*/
  const getCustomerRequireList = async () => {
    const { responseData } = await getCustomerRequireData()
    list.value = responseData || []
  }

  /** 关联需求单 来源  */
  const handleCustomerChange = () => {
    if (formState.customerRequireId) {
      formState.requireSource = list.value.find((item) => item.id === formState.customerRequireId)?.accountName || ''
    }
  }
  /**获取详情*/
  const getDetail = async () => {
    const params: any = { platformRequireId: platformRequireId }
    const { responseData } = await getRequireDetail(params)
    if (responseData) {
      const detailData = responseData
      // formState = responseData
      // detailData.value = responseData
      const labelList = responseData.labels ? JSON.parse(responseData.labels) : []
      const _dictResultValue = responseData.dictResults
        ? responseData.dictResults.values.map((item) => {
            return {
              key: item.code,
              label: item.name,
            }
          })
        : []
      const _fileList: any = responseData.sampleTemp
        ? responseData.sampleTemp.map((item) => {
            return {
              name: item.fileName,
              type: item.fileType,
              size: item.fileSize,
              status: 'done',
            }
          })
        : []

      sampleTemp.value = responseData.sampleTemp || []
      detailData.labels = labelList
      Object.assign(formState, detailData, { requireTime: [responseData.requireBeginTime, responseData.requireEndTime], dictResultValue: _dictResultValue, sampleTempList: _fileList })
      if (responseData.customerRequireFlag === 1) {
        formState.customerRequireId = responseData.assRequire && responseData.assRequire.id ? Number(responseData.assRequire.id) : ''
      } else {
        formState.customerRequireId = undefined
      }
    }
  }

  onMounted(() => {
    getDictData()
    getCustomerRequireList()
    if (platformRequireId) {
      getDetail()
    }
  })
</script>
<style lang="less" scoped>
  .avatar-uploader > .ant-upload {
    width: 128px;
    height: 128px;

    .logo-img {
      width: 100%;
      height: 100%;
    }
  }

  .ant-upload-select-picture-card .ant-upload-text {
    margin-top: 8px;
    color: #666;
  }

  .create-box {
    width: 100%;
    padding: 0 24px 30px;
    background: #fff;
    border-radius: 2px;

    .header {
      width: 100%;
      height: 64px;
      margin-bottom: 20px;
      border-bottom: 1px solid #f2f3f5;
      font-size: 16px;
      font-weight: bold;
      color: #000;
      line-height: 64px;
    }

    .create-title {
      padding-left: 20px;
      margin-bottom: 10px;
      font-size: 16px;
      color: #000;
    }

    .create-order-select {
      margin-top: 20px;
    }

    .back-btn {
      margin-left: 20px;
    }

    .label-box {
      width: 100%;
      display: flex;
      align-items: center;

      .label-btn {
        width: 32px;
        height: 32px;
        border-radius: 50%;
        background: #08979c;
        text-align: center;
        font-size: 24px;
        line-height: 32px;
        color: #fff;
        cursor: pointer;
      }

      .label-btn,
      .label-list {
        margin-left: 20px;
      }

      .label-item {
        margin-right: 10px;
      }
    }
  }
</style>
